package com.baocai.tools.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @author ：minyang
 * @date ：Created in 2020/4/7 19:17
 * 复制工具类
 */
public class CopyUtils {


    public static List copyList(List sourceList, Class<?> targetClass) {
        List<?> objectList = com.alibaba.fastjson.JSONArray.parseArray(JSON.toJSONString(sourceList), targetClass);
        return objectList;
    }

    public static List copyList(List sourceList, Class<?> targetClass, String sourceDetailPkFieldName) {
        if (!StringUtils.isEmpty(sourceDetailPkFieldName)) {
            try {
                Field field = existsField(sourceList.get(0), sourceDetailPkFieldName);
                field.setAccessible(true);
                Object fieldValue = field.get(sourceList.get(0));
                if (!ObjectUtils.isEmpty(fieldValue)) {
                    List<?> objectList = com.alibaba.fastjson.JSONArray.parseArray(JSON.toJSONString(sourceList), targetClass);
                    return objectList;
                }
            } catch (IllegalAccessException var6) {
                var6.printStackTrace();
            }
        }

        return null;
    }

    private static Field existsField(Object obj, String fieldName) {
        Field field = null;

        try {
            field = obj.getClass().getDeclaredField(fieldName);
        } catch (NoSuchFieldException var5) {
            ;
        }

        if (ObjectUtils.isEmpty(field)) {
            try {
                field = obj.getClass().getSuperclass().getDeclaredField(fieldName);
            } catch (NoSuchFieldException var4) {
                ;
            }
        }

        return field;
    }
}
